package com.acpt.service;


import com.acpt.common.CacheConstants;
import com.acpt.entity.LoginUser;
import com.acpt.util.RedisCache;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class TokenService {

  @Autowired
  protected HttpServletRequest request;
  @Autowired
  private RedisCache redisService;

  public String getUserIdByToken(String token) {
    Object obj = redisService.getCacheObject(getTokenKey(token));
    if (obj != null) {
      return (String) obj;
    }
    return null;
  }

  public LoginUser getUserByUserId(String userId) {
    Object obj = redisService.getCacheObject(getUserKey(userId));
    if (obj != null) {
      return (LoginUser) obj;
    }
    return null;
  }

  public LoginUser getLoginUser() {

    LoginUser loginUser = null;
    String authorization = request.getHeader("Authorization");
    if (StringUtils.isEmpty(authorization)) {
      return null;
    }
    // 获取请求携带的令牌
    String token = authorization.replace("Bearer ", "");
    if (StringUtils.isEmpty(token)) {
      return null;
    }
    try {
      String userId = null;
      String tokenKey = getTokenKey(token);
      if (StringUtils.isNotEmpty(tokenKey)) {
        userId = (String) redisService.getCacheObject(tokenKey);
        // 解析对应的权限以及用户信息
        String userKey = getUserKey(userId);
        loginUser = (LoginUser) redisService.getCacheObject(userKey);
      }
      return loginUser;
    } catch (Exception e) {
      log.error("从缓存获取用户信息异常:{}", e.getMessage());
      throw new RuntimeException("用户获取失败，请重新登录！");
    }
  }

  private String getTokenKey(String token) {
    return CacheConstants.LOGIN_TOKEN_KEY + token;
  }

  private String getUserKey(String userId) {
    return CacheConstants.LOGIN_USER_KEY + userId;
  }
}


